import React, {ChangeEvent, useEffect, useState} from "react";
import Chain from "../../models/Chain";
import {getChainById, getChains} from "../../http/chainApi";
import './styles/ProjectsListPage.css'
import routeNames from "../../utils/routeNames";
import {useNavigate} from "react-router-dom";
import {getPaginationRange} from "../../functions/getPaginationRange";
import Token from "../../models/Token";
import {getImageById} from "../../http/imageApi";
import {getTokens} from "../../http/tokenApi";
import GetTokensDto from "../../utils/dto/token/getTokensDto";
import handleImageNotLoaded from "../../functions/handleImageNotLoaded";

const ProjectsListPage = () => {
    const navigate = useNavigate()
    const [chains, setChains] = useState<Chain[]>([]);
    const [pageNumber, setPageNumber] = useState(1);
    const [pageSize] = useState(15);
    const [filter, setFilter] = useState(localStorage.getItem('ProjectsListPageSearchValue') ?? "");
    const [searchTrigger, setSearchTrigger] = useState(false);
    const [totalPages, setTotalPages] = useState(1);
    const [tokens, setTokens] = useState<{ token: Token; chain: Chain }[]>([]);
    const [selectedChain, setSelectedChain] = useState<string>(""); // Состояние для отслеживания выбранной цепочки

    const fetchTokens = async () => {
        let dto = new GetTokensDto(pageNumber, pageSize, filter);
        const response = await getTokens(dto);
        if (response.status === 200) {
            const tokenPromises = response.data.tokens.map(async (token: Token) => {
                const chainResponse = await getChainById(token.chainId);
                return {token, chain: chainResponse.data};
            });
            const tokensWithChains = await Promise.all(tokenPromises);
            const filteredTokens = selectedChain ? tokensWithChains.filter(token => token.chain.name === selectedChain) : tokensWithChains;
            setTokens(filteredTokens);
            let newTotalPages = Math.ceil(response.data.count / pageSize);
            setTotalPages(newTotalPages === 0 ? 1 : newTotalPages);
        } else {
            console.error(response.statusText);
        }
    };

    useEffect(() => {
        fetchTokens().catch(error => console.error(error));
    }, [pageNumber, searchTrigger, selectedChain]);

    const handlePageChange = (newPageNumber: number) => {
        setPageNumber(newPageNumber);
    };

    const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
        setFilter(e.target.value);
        localStorage.setItem('ProjectsListPageSearchValue', e.target.value)
    };

    const handleSearchClick = () => {
        setTokens([]);
        setSearchTrigger(prevState => !prevState);
        setPageNumber(1);
    };

    useEffect(() => {
        getChains().then(response => {
            if (response.status === 200)
                setChains(response.data.chains)
            else
                alert(response.statusText)
        })
    }, []);

    const handleChainChange = (e: ChangeEvent<HTMLSelectElement>) => {
        let selectedChainName = e.target.value;
        if (selectedChainName === "All Block Chain") {
            selectedChainName = ''
        }
        setSelectedChain(selectedChainName);
    };

    return (
        <>
            <div className="gamfi-breadcrumbs-section">
                <div className="container">
                    <div className="row">
                        <div className="col-lg-5">
                            <div className="breadcrumbs-area sec-heading">
                                <div className="sub-inner mb-15">
                                    <a className="breadcrumbs-link" onClick={() => navigate(routeNames.HOME_PAGE)}
                                       style={{cursor: 'pointer'}}>Home</a>
                                    <span className="sub-title">Projects</span>
                                    <img className="heading-left-image" src="/assets/images/icons/steps.png"
                                         alt="Steps-Image"/>
                                </div>
                                <h2 className="title mb-0">Explore Igos</h2>
                            </div>
                        </div>
                        <div className="col-lg-7 breadcrumbs-form md-pt-30">
                            <div>
                                <input type="text" id="Search" name="search"
                                       placeholder="Search by name" onChange={handleSearchChange}/>
                                <span className="submit" onClick={handleSearchClick}><i
                                    className="icon-search"></i><input type="submit"/></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="gamfi-previous-section pt-70 pb-120 md-pb-80">
                <div className="container">
                    <div className="project-menu-area d-flex align-items-center justify-content-between">
                        <div className="project-left-menu"></div>
                        <div className="project-right-menu">
                            <select value={selectedChain} onChange={handleChainChange}>
                                {chains.sort((a, b) => a.name.localeCompare(b.name)).map(chain => (
                                    <option key={chain.id} value={chain.name}
                                            style={{cursor: 'pointer'}}>{chain.name}</option>))}
                            </select>
                        </div>
                    </div>
                    <div className="tab-content" id="myTabContent">
                        <div className="tab-pane fade show active" role="tabpanel"
                             aria-labelledby="home-tab">
                            <div className="row align-items-center">
                                <div className="col-md-12">
                                    <div className="previous-mainmenu mb-15">
                                        <ul className="menu-list">
                                            <li className="list1">Project name</li>
                                            <li className="list2">Chain</li>
                                            <li className="list3">Launched</li>
                                            <li className="list4">Total Raise</li>
                                            <li className="list5">Progress</li>
                                        </ul>
                                    </div>
                                    {tokens.map(token => (
                                        <a key={token.token.id}
                                           onClick={() => navigate(routeNames.PROJECT_DETAILS_PAGE, {state: {tokenId: token.token.id}})}>
                                            <div className="previous-item hover-shape-border hover-shape-inner">
                                                <div className="previous-gaming">
                                                    <div className="previous-image">
                                                        <img src={getImageById(token.token.imageId)}
                                                             onError={handleImageNotLoaded}
                                                             alt="Previous-Image"/>
                                                    </div>
                                                    <div className="previous-price">
                                                        <h4 className="mb-10">{token.token.name}</h4>
                                                        <div className="dsc">price ({token.token.tokenSymbol})
                                                            = {token.token.tokenPrice} BUSD
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="previous-chaining">
                                                    <img src={getImageById(token.chain.imageId)}
                                                         onError={handleImageNotLoaded} alt="Chain-Image"/>
                                                    <div className="counter-info">
                                                        <ul>
                                                            <li><span
                                                                className="counter">{new Date(token.token.createdDate).getDay()}</span>D
                                                            </li>
                                                            <li><span
                                                                className="counter">{new Date(token.token.createdDate).getHours()}</span>H
                                                            </li>
                                                            <li><span
                                                                className="counter">{new Date(token.token.createdDate).getMinutes()}</span>M
                                                            </li>
                                                            <li><span
                                                                className="counter">{new Date(token.token.createdDate).getSeconds()}</span>S
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div className="previous-raise">
                                                    <span>{token.token.totalRaise} BUSD ({((token.token.totalRaise / token.token.targetedRaise) * 100).toFixed(2)}%)</span>
                                                    <div className="progress-inner">
                                                        <div className="progress">
                                                            <div className="progress-bar progress-bar-striped"
                                                                 role="progressbar"
                                                                 aria-valuenow={parseFloat(((token.token.totalRaise / token.token.targetedRaise) * 100).toFixed(2))}
                                                                 aria-valuemin={0}
                                                                 aria-valuemax={100}
                                                                 style={{width: `${((token.token.totalRaise / token.token.targetedRaise) * 100).toFixed(2)}%`}}>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <span className="border-shadow shadow-1"></span>
                                                <span className="border-shadow shadow-2"></span>
                                                <span className="border-shadow shadow-3"></span>
                                                <span className="border-shadow shadow-4"></span>
                                                <span className="hover-shape-bg hover_shape1"></span>
                                                <span className="hover-shape-bg hover_shape2"></span>
                                                <span className="hover-shape-bg hover_shape3"></span>
                                            </div>
                                        </a>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="gamfi-navigation text-center mt-40">
                        <ul>
                            <li>
                                <a
                                    onClick={() => pageNumber > 1 && handlePageChange(pageNumber - 1)}
                                    className={pageNumber === 1 ? "disabled" : ""}
                                    style={{cursor: pageNumber === 1 ? "default" : "pointer"}}
                                >
                                    <i className="icon-Vector"></i>
                                </a>
                            </li>
                            {getPaginationRange(pageNumber, pageSize, totalPages).map((page, index) => (
                                <li key={index}>
                                    <a
                                        style={{cursor: page === '...' ? 'default' : 'pointer'}}
                                        className={pageNumber === page ? "active" : ""}
                                        onClick={() => typeof page === 'number' && handlePageChange(page)}
                                    >
                                        {page}
                                    </a>
                                </li>
                            ))}
                            <li>
                                <a
                                    onClick={() => pageNumber < totalPages && handlePageChange(pageNumber + 1)}
                                    className={pageNumber === totalPages ? "disabled" : ""}
                                    style={{cursor: pageNumber === totalPages ? "default" : "pointer"}}
                                >
                                    <i className="icon-arrow_right"></i>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>

            </div>

        </>
    )
}

export default ProjectsListPage